<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: rclark $ ($Date: 2007/07/19 22:33:16 $)
// $RCSfile: impex.tickets.php,v $ : $Revision: 1.2 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");

/**
* Return the Total Pages for this Plugin
*/
function getPluginTotalPages1()
{
	global $impexDB;

	$_total = $impexDB->queryFetch("SELECT COUNT(*) AS totaltickets FROM `ticket`;");
	$finaltotal = intval($_total["totaltickets"]);

	$totalpages = ceil($finaltotal/IMPEX_PASS)+1;

	return $totalpages;
}

/**
* Generate a random Ticket Mask
*/
function generateTicketMask()
{
	global $_SWIFT;

	mt_srand ((double) microtime() * 1000000);
	$alpha1 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha2 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha3 = mt_rand(65,90);

	$alpha1 = chr($alpha1);
	$alpha2 = chr($alpha2);
	$alpha3 = chr($alpha3);

	// This was a serious issue in v2, The stupid computer would come up with words like GAY and client would be pissed as hell.
	$prefix = $alpha1.$alpha2.$alpha3;
	if (in_array(strtoupper($prefix), $_SWIFT["stopwords"]))
	{
		return generateTicketMask();
	}

	mt_srand ((double) microtime() * 1000000);
	$num = mt_rand(100000,999999);
	$ticketmaskid = $alpha1 . $alpha2 . $alpha3 . "-" . $num;

	return $ticketmaskid;
}

/**
* Run the specific page for plugin
*/
function runPluginPage1($page)
{
	global $dbCore, $impexDB, $_IMPEXHASH, $_SWIFT;

	// Import Predefined Replies
	if ($page == 1)
	{
		$predefinedcategoryid = _impexInsertPredefinedCategory(0, "Impex");

		$predefinedreplies = array();
		$impexDB->query("SELECT * FROM `email_templates` ORDER BY `template_id` ASC;");
		while ($impexDB->nextRecord())
		{
			$predefinedreplies[$impexDB->Record["template_id"]] = $impexDB->Record;
		}

		foreach ($predefinedreplies as $key=>$val)
		{
			_impexInsertPredefinedReply($predefinedcategoryid, $val["template_name"], $val["template_text"]);

			displayStatus("Imported Predefined Reply: ".htmlspecialchars($val["template_name"]));
		}

	// Import Tickets
	} else {
		// Import Tickets! The big tough crap function.
		if (empty($_POST["ticketstartat"]))
		{
			$_startat = 1;
		} else {
			$_startat = intval($_POST["ticketstartat"]);
		}

		$ticketidlist = $ticketlist = $ticketidcharlist = $ticketidpointer = $newticketpointer = array();

		// First get all the tickets
		$impexDB->query("SELECT * FROM `ticket` WHERE `ticket_id` >= '". intval($_startat) ."' ORDER BY `ticket_id` ASC LIMIT ". intval(IMPEX_PASS) .";");
		while ($impexDB->nextRecord())
		{
			$ticketidlist[] = $impexDB->Record["ticket_id"];
			$ticketidcharlist[] = $impexDB->Record["ticket_mask"];
			$ticketidpointer[$impexDB->Record["ticket_mask"]] = $impexDB->Record["ticket_id"];
			$ticketlist[$impexDB->Record["ticket_id"]] = $impexDB->Record;
			$ticketlist[$impexDB->Record["ticket_id"]]["posts"] = array();
			$ticketlist[$impexDB->Record["ticket_id"]]["replies"] = 0;
			$lastticketid = $impexDB->Record["ticket_id"];
		}
//		print_r($ticketlist);

		// Now load in the threads for this ticket
		$threads = $threadidlist = $threadpointer = $addresslist = array();
		$impexDB->query("SELECT * FROM `thread` WHERE `ticket_id` IN (". buildIN($ticketidlist) .") ORDER BY `thread_id` ASC;");
		while ($impexDB->nextRecord())
		{
			$threads[$impexDB->Record["thread_id"]] = $impexDB->Record;
			$threadidlist[] =$impexDB->Record["thread_id"];
			$threadpointer[$impexDB->Record["thread_id"]] = $impexDB->Record["ticket_id"];
			$addresslist[] = $impexDB->Record["thread_address_id"];
		}

		// Load the content parts
		$impexDB->query("SELECT * FROM `thread_content_part` WHERE `thread_id` IN (". buildIN($threadidlist) .") ORDER BY `content_id` ASC;");
		while ($impexDB->nextRecord())
		{
			$threads[$impexDB->Record["thread_id"]]["contents"] .= $impexDB->Record["thread_content_part"];
		}

		// Load the Email Address of all thread users
		$addresspointer = $ticketnotes = array();
		$impexDB->query("SELECT * FROM `address` WHERE `address_id` IN (". buildIN($addresslist) .") ORDER BY `address_id` ASC;");
		while ($impexDB->nextRecord())
		{
			$addresspointer[$impexDB->Record["address_id"]] = $impexDB->Record["address_address"];
		}

		// By now we have all the data, load in the posts
		foreach ($threads as $key=>$val)
		{
			$ticket_id = $val["ticket_id"];

			if ($val["thread_type"] == "comment")
			{
				$noteindex = count($ticketnotes[$ticket_id]);
				$_ticketnote = $ticketnotes[$ticket_id][$noteindex];
				$_ticketnote = array();
				$_ticketnote["dateline"] = returnUNIXTimestamp($val["thread_date"]);
				$_ticketnote["fullname"] = $addresspointer[$val["thread_address_id"]];
				$_ticketnote["email"] = $addresspointer[$val["thread_address_id"]];
				$_ticketnote["contents"] = $val["contents"];
				$_ticketnote["ticket_id"] = $val["ticket_id"];
			} else {
				$postindex = count($ticketlist[$ticket_id]["posts"]);
				if ($postindex == 0)
				{
					$ticketlist[$ticket_id]["fullname"] = $addresspointer[$val["thread_address_id"]];
					$ticketlist[$ticket_id]["email"] = $addresspointer[$val["thread_address_id"]];
				}
				$ticketlist[$ticket_id]["lrby"] = $addresspointer[$val["thread_address_id"]];
				$ticketlist[$ticket_id]["replies"]++;

				$_ticketpost = &$ticketlist[$ticket_id]["posts"][$postindex];
				$_ticketpost = array();
				$_ticketpost["dateline"] = returnUNIXTimestamp($val["thread_date"]);
				$_ticketpost["fullname"] = $addresspointer[$val["thread_address_id"]];
				$_ticketpost["email"] = $addresspointer[$val["thread_address_id"]];
				$_ticketpost["subject"] = $val["thread_subject"];
				$_ticketpost["ipaddress"] = "";
				$_ticketpost["creator"] = iif($val["is_agent_message"]==1, POST_STAFF, POST_CLIENT);
				$_ticketpost["contents"] = $val["contents"];
				$_ticketpost["ticket_id"] = $val["ticket_id"];
			}
		}

		// By now, almost all data should be loaded.. insert the tickets first
		foreach ($ticketlist as $key=>$val)
		{
//			print_r($val);
			$newdepartmentid = intval($_IMPEXHASH["departmentpointer"][$val["ticket_queue_id"]]);
			$newemailqueueid = $_IMPEXHASH["queuepointer"][$val["ticket_queue_id"]];
			$newownerstaffid = $_IMPEXHASH["staffpointer"][$val["ticket_assigned_to_id"]];
			if (empty($newdepartmentid))
			{
				displayStatus("<font color='red'>WARNING:</font> Ticket ".$val["ticketid"]." does not have a valid department. Ignoring.");
			} else {
				if ($val["ticket_status"] == "new")
				{
					$newticketstatus = 1;
				} else if ($val["ticket_status"] == "awaiting-reply" || $val["ticket_status"] == "customer-reply" || $val["ticket_status"] == "hold") {
					$newticketstatus = 2;
				} else {
					$newticketstatus = 3;
				}

				$ticketid = _impexInsertTicket(iif(!empty($val["ticket_mask"]), substr($val["ticket_mask"],0,9), generateTicketMask()), $newdepartmentid, $newticketstatus, 1, intval($newemailqueueid), "0", "0", intval($newownerstaffid), $val["fullname"], $val["email"], $val["lrby"], $val["ticket_subject"], returnUNIXTimestamp($val["ticket_date"]), returnUNIXTimestamp($val["last_update_date"]), iif($val["replies"]>0, ($val["replies"]-1), 0), POST_CLIENT);

				foreach ($val["posts"] as $postkey=>$postval)
				{
//					echo "Inserting Ticket Post: ". $postval["fullname"] ." For: ". $ticketid ."<BR />";
					_impexInsertTicketPost($ticketid, $postval["dateline"], "0", $postval["fullname"], $postval["email"], "", $postval["subject"], $postval["ipaddress"], $postval["creator"], 0, 0, $postval["contents"]);
					$lastreplier = $postval["fullname"];
				}

				$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `lastreplier` = '". $dbCore->escape(iif(empty($lastreplier), $val["fullname"], $lastreplier)) ."' WHERE `ticketid` = '". intval($ticketid) ."';");
				$newticketpointer[$val["ticket_id"]] = $ticketid;

				displayStatus("Imported Ticket: #".iif(!empty($val["ticket_mask"]), $val["ticket_mask"], $val["ticket_id"]));
			}
		}

		unset($ticketlist);
		// Time to import all ticket notes...
		foreach ($ticketnotes as $key=>$val)
		{
			$newstaffid = intval($_IMPEXHASH["staffemailpointer"][$val["email"]]);
			$ticketid = $newticketpointer[$val["ticket_id"]];

			_impexInsertTicketNote($ticketid, NOTE_TICKET, 0, $newstaffid, $val["dateline"], $val["contents"]);

			_impexTagTicketHasNotes($ticketid);
		}
		unset($notes);

		$_SWIFT["ticketstartat"] = $lastticketid+1;
	}
}
?>